package uk.co.droidinactu.sony.prst1.home.data;

import java.io.File;

import uk.co.droidinactu.inlibrislibertas.model.EBook;
import uk.co.droidinactu.inlibrislibertas.model.MimeTypes;
import uk.co.droidinactu.sony.prst1.home.EditPreferences;
import uk.co.droidinactu.sony.prst1.home.R;
import uk.co.droidinactu.sony.prst1.home.db.SonyDatabaseController;
import uk.co.droidinactu.sony.prst1.home.view.Page2Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;

public final class DataModel {

	private static final String LOG_TAG = "DataModel";
	SonyDatabaseController dbCntlr;

	public DataModel(final Context ctx) {
		dbCntlr = new SonyDatabaseController(ctx);
		openDb();
	}

	public void closeDb() {
		dbCntlr.close();
	}

	public Book getBook(final Context cntxt, final long id) {
		final Cursor c = dbCntlr.getAll(new Book().getTableName(), null, "_id=?", new String[] { "" + id },
				null, null, null);
		c.moveToFirst();
		Book b = new Book(c);
		c.close();
		return b;
	}

	public Cursor getBooks(final Context cntxt) {
		final Cursor c = dbCntlr.getAll(new Book());
		c.moveToFirst();
		return c;
	}

	public Cursor getBooks(final Context cntxt, final String filterStr) {
		final String sqlStr = "select * from books where title like '" + filterStr + "%'";
		final Cursor cur = dbCntlr.execSql(sqlStr, null);
		cur.moveToFirst();
		return cur;
	}

	public Cursor getBooksInCollection(final Context cntxt, final Collection clctn) {
		return getBooksInCollection(cntxt, clctn.title);
	}

	public Cursor getBooksInCollection(final Context cntxt, final String collectionName) {
		final String sqlStr = "select books.* from books,collection,collections where books._id=collections.content_id and collections.collection_id=collection._id and collection.title=?";
		return dbCntlr.execSql(sqlStr, new String[] { collectionName });
	}

	public Cursor getBooksInCollection(final Context cntxt, final String collectionName, int start, int end) {
		final String sqlStr = "select books.* from books,collection,collections where books._id=collections.content_id and collections.collection_id=collection._id and collection.title=? limit "
				+ start + "," + end;
		return dbCntlr.execSql(sqlStr, new String[] { collectionName });
	}

	public Collection getCollection(final Context cntxt, final long id) {
		final Cursor c = dbCntlr.getAll(new Collection().getTableName(), null, "_id=?", new String[] { ""
				+ id }, null, null, null);
		c.moveToFirst();
		Collection b = new Collection(c);
		c.close();
		return b;
	}

	private Collection getCollection(final String collectionName) {
		final Cursor c = dbCntlr.getAll(new Collection().getTableName(), null, "title=?",
				new String[] { collectionName }, null, null, null);
		c.moveToFirst();
		Collection b = new Collection(c);
		c.close();
		return b;
	}

	public String[] getCollectionNames() {
		final String sqlStr = "select title from collection";
		final Cursor cur = dbCntlr.execSql(sqlStr, null);
		final String[] retVal = new String[cur.getCount()];
		cur.moveToFirst();
		int x = 0;
		while (cur.isAfterLast() == false) {
			final Object tmpObj = cur.getString(0);
			retVal[x++] = tmpObj.toString();
			cur.moveToNext();
		}
		cur.close();
		return retVal;
	}

	public Cursor getCollections() {
		final Cursor c = dbCntlr.getAll(new Collection().getTableName(), null, null, null, null, null,
				Collection.COLUMN_NAME_TITLE + " ASC");
		c.moveToFirst();
		return c;
	}

	public Cursor getCollections(final Context cntxt) {
		final Cursor c = dbCntlr.getAll(new Collection().getTableName(), null, null, null, null, null,
				Collection.COLUMN_NAME_TITLE + " ASC");
		c.moveToFirst();
		return c;
	}

	public Bitmap getCoverImg(final Context cntxt, final String thumbnailFilename) {
		Bitmap bitmap = BitmapFactory.decodeFile("/mnt/sdcard/" + thumbnailFilename);
		if (bitmap == null) {
			bitmap = BitmapFactory.decodeFile("/mnt/extsd/" + thumbnailFilename);
		}
		if (bitmap == null) {
			bitmap = BitmapFactory.decodeResource(cntxt.getResources(),
					R.drawable.ic_missing_thumbnail_picture);
		}
		return bitmap;
	}

	public Cursor getCurrentlyReading(final Context cntxt) {
		final int nbrItems = EditPreferences.getCurrentReadDuration(cntxt);
		return dbCntlr.getAll(new Book().getTableName(), null, "reading_time not null", null, null, null,
				"reading_time desc", "0," + nbrItems);
	}

	public Cursor getCurrentlyReading(final Context cntxt, int start, int end) {
		final int nbrItems = EditPreferences.getCurrentReadDuration(cntxt);
		return dbCntlr.getAll(new Book().getTableName(), null, "reading_time not null", null, null, null,
				"reading_time desc", start + "," + end);
	}

	public Cursor getPictures(final Page2Activity page2Activity) {
		return null;
	}

	public void launchBook(final Context cntxt, final long id) {
		final Book bk = getBook(cntxt, id);
		final Intent intent = new Intent();
		intent.setAction(android.content.Intent.ACTION_VIEW);
		File file = new File("/mnt/sdcard/" + bk.file_path);
		if (!file.exists()) {
			file = new File("/mnt/extsd/" + bk.file_path);
		}
		String filetype = bk.mime_type;
		if (filetype == null) {
			filetype = "application/epub+zip";
		}
		intent.setDataAndType(Uri.fromFile(file), filetype);
		cntxt.startActivity(intent);
	}

	public void launchBookCalibre(final Context cntxt, final EBook bookDetails) {
		// launch Intent to show book in reader on e-ink side
		final String sdCardDir = "/mnt/extsd/";
		final Intent intent = new Intent();
		intent.setAction(android.content.Intent.ACTION_VIEW);
		final File file = new File(sdCardDir + File.separator + bookDetails.lpath);
		String filetype = bookDetails.mime;
		if (filetype.equalsIgnoreCase("null")) {
			if (bookDetails.lpath.endsWith("epub")) {
				filetype = MimeTypes.MIME_TYPE_EPUB;
			} else if (bookDetails.lpath.endsWith("pdf")) {
				filetype = MimeTypes.MIME_TYPE_PDF;
			}
		}
		intent.setDataAndType(Uri.fromFile(file), filetype);
		cntxt.startActivity(intent);
	}

	public void openDb() {
		dbCntlr.open();
	}

}
